﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using TCommon.Enum;
using TRTC;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Runtime.Serialization;
using TCommon.Entity;
using TCommon;
using Newtonsoft.Json;
using ManageLiteAV;

namespace TRTCMain
{
    public partial class InputUserNameForm : Form
    {
        private int roomId;
        private UserRole role;
        private string UserSign;
        private string HostId;
        private string UserId;
        private Window loginWindow;
        bool isConfirmed = false;
        private ITRTCCloud mTRTCCloud;

        public delegate void NameChangedHandler(string userName);
        public event NameChangedHandler NameChanged;

        public InputUserNameForm(int roomId, Window loginWindow, string userSign, string hostId, string userId, UserRole role = UserRole.Participant)
        {
            this.loginWindow = loginWindow;
            this.roomId = roomId;
            this.role = role;
            this.UserId = userId;
            this.UserSign = userSign;
            this.HostId = hostId;
            InitializeComponent();
        }

        public InputUserNameForm(ITRTCCloud cloud, string userName) {
            this.UserId = userName;
            this.mTRTCCloud = cloud;
            InitializeComponent();
        }

        private void btnConfrim_Click(object sender, EventArgs e)
        {
            var name = this.userNameEdit.Text;

            var action = new ActionEntity();
            action.UserId = this.UserId;
            action.UserName = name;
            var actionString = JsonConvert.SerializeObject(action);
            var data = Encoding.UTF8.GetBytes(actionString);
            mTRTCCloud?.sendCustomCmdMsg(MessageId.ChangeName, data, (uint)data.Length, true, true);
            NameChanged?.Invoke(name);
            //var userName = UserId + "$$$" + name;
            //var sign = GetUserSign(this.roomId, userName);
            //var host = this.HostId;
            //var form = new VideoMainForm(this.loginWindow, this.roomId, userName, host, sign, this.role);
            ////form.WindowState = FormWindowState.Maximized;
            //form.Show();
            //isConfirmed = true;
            this.Close();
        }

        private string GetUserSign(int roomId, string userName)
        {
            string sign = "";
            try
            {
                var urlFormat = "https://www.1meeting.cn/getusersig?roomid={0}&userid={1}";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(urlFormat, roomId, userName));
                var param = new object()
                {

                };
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(object));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, param);
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                string dataString = Encoding.UTF8.GetString(dataBytes);
                stream.Close();
                request.Method = "POST";
                request.ContentType = "application/json";

                var requestByte = Encoding.UTF8.GetBytes(dataString);
                request.ContentLength = requestByte.Length;
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(requestByte, 0, requestByte.Length);
                    var response = (HttpWebResponse)request.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    var returnString = sr.ReadToEnd();
                    var responseStream = new MemoryStream(Encoding.UTF8.GetBytes(returnString));
                    DataContractJsonSerializer seri = new DataContractJsonSerializer(typeof(UserSig));
                    var res = (UserSig)seri.ReadObject(responseStream);
                    if (res != null)
                    {
                        sign = res.UserSign;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("获取会议秘钥失败");
            }

            return sign;
        }

        private void InputUserNameForm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }
    }

    [DataContract]
    public class UserSig
    {
        [DataMember(Name = "usersig")]
        public string UserSign { get; set; }
    }
}
